/*
 * @Author: 陈伟 chenwei@duoliheng.com
 * @Date: 2022-07-13 10:56:14
 * @LastEditors: 陈伟 chenwei@duoliheng.com
 * @LastEditTime: 2022-11-07 17:34:40
 * @FilePath: \cool.front\src\permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
// import showNoticeDialog from '@/views/components/NoticeDialog/index.js'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration
// const noticeFlag = true
const whiteList = ['/login', 'https://www.baidu.com', '/components/phoneUpload'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  if (whiteList.indexOf(to.path) !== -1) {
    next()
  } else {
    const hasGetUserInfo = store.getters.userInfo
    if (hasGetUserInfo) {
      // if (noticeFlag && store.getters.userInfo.showRN === 61) {
      //   noticeFlag = false
      //   showNoticeDialog()
      // }
      next()
    } else {
      try {
        // get user info
        await store.dispatch('user/getInfo')
        // generate accessible routes map based on roles
        const accessRoutes = await store.dispatch('permission/generateRoutes')
        // console.log('route')
        // console.log(accessRoutes)
        if (store.getters.userInfo) {
          // 获取组织机构数据
          await store.dispatch('user/getOrgData')
          // 获取流程配置数据
          await store.dispatch('user/getCorpSettingData')
        }
        // dynamically add accessible routes
        router.addRoutes(accessRoutes)
        // if (noticeFlag && store.getters.userInfo.showRN === 61) {
        //   noticeFlag = false
        //   showNoticeDialog()
        // }
        if (from.path === '/login' && router.match(to).path === '/404') {
          next({ path: '/', replace: true })
        } else {
          next({ ...to, replace: true })
        }
      } catch (error) {
        if (error.errorCode === 401 && process.env.NODE_ENV === 'production') {
          // if (error.errorCode === 401) {
          // 关闭弹窗
          document.querySelector('.messageBox401 .el-button').click()
          await store.dispatch('user/logout', true)
        }
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
